package com.flashcash.solu.view.certification;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants;
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils;
import com.flashcash.kotlin.widget.LocalButton;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.BaseActivity;
import com.flashcash.solu.bean.ContactInfoBean;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.FieldParamsInt;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.utils.ACache;
import com.flashcash.solu.view.IntroduceActivity;
import com.flashcash.solu.view.certification.presenter.ContactInfoActPreImp;
import com.flashcash.solu.view.certification.presenter.ContactInfoActPresenter;
import com.flashcash.solu.widget.MyEditTextView;
import com.flashcash.solu.widget.stepview.HorizontalStepView;
import com.flashcash.solu.widget.stepview.bean.StepBean;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.x.leo.apphelper.data.cache.CacheDataManage;
import com.x.leo.apphelper.log.XLog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

/**
 * Created by Miaoke on 2017/2/27.
 */

public class ContactInfoActivity extends BaseActivity<ContactInfoActPresenter> implements ContactInfoView {

    private static final String SAVE_INSTANCE_IS_EDITABLE = "save_instance_is_editable";
    public static final String KEY_STEP_VIEW_VISIBLE = "step_view_visible";

    //    @BindView(R.id.id_imagebutton_contact_info_father_mother)
//    ImageButton contact;
//    @BindView(R.id.id_edittext_contact_info_father_mother_name)
//    LocalTextView parentName;
    @BindView(R.id.id_textview_contact_info_father_mother_telephone)
    MyEditTextView parentPhone;
    //    @BindView(R.id.id_textview_contact_info_friend_name)
//    LocalTextView friendName;
    @BindView(R.id.id_textview_contact_info_friend_elephone)
    MyEditTextView friendPhone;
    @BindView(R.id.id_textview_title)
    TextView title;
    @BindView(R.id.id_imagebutton_info_list)
    ImageButton infoList;
    @BindView(R.id.id_button_contact_info_submit)
    LocalButton contactInfoSubmit;
    @BindView(R.id.step_view)
    HorizontalStepView stepView;

    private boolean isEditable = false;
    private Bundle mSavedInstaceState = null;

    private String parentName, friendName;

    private boolean stepViewVisible;//进度条是否可见
    private boolean notFinish;
    private boolean fromSplash;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mSavedInstaceState = savedInstanceState;
        super.onCreate(savedInstanceState);
        RxBus.get().register(this);
    }

    /**
     * 完成四步认证
     *
     * @param event
     */
    @Subscribe
    public void onFinish(EventCollection.FirstFinishCertifyEvent event) {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.EXPOSURE_CONTACT_INFO, null);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_contacts_info;
    }

    public void onBackPressed() {
        super.onBackPressed();

        if (localInputExist() && !identicalToServer()) {

            saveLocalInput();

            XLeoToast.initXLeoToast(this);
            XLeoToast.showMessage(this.getString(R.string.change_not_upload));
        } else {
            removeAllLocal();
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void init() {
        Intent intent = getIntent();
        if (intent != null) {
            stepViewVisible = intent.getBooleanExtra(KEY_STEP_VIEW_VISIBLE, true);
            notFinish = getIntent().getBooleanExtra(FieldParams.NOT_FINISH_CERTIFY, false);
            fromSplash = getIntent().getBooleanExtra(FieldParams.FROM_SPLASH, false);
            if (notFinish) {
                stepViewVisible = true;
            }
        }

        Boolean aBoolean = CacheDataManage.INSTANCE.obtainData(FieldParamsInt.INFO_EDITABLE, Boolean.class);
        isEditable = aBoolean != null && aBoolean;
        if (mSavedInstaceState != null) {
            isEditable = mSavedInstaceState.getBoolean(SAVE_INSTANCE_IS_EDITABLE, false);
            if (isEditable) {
                CacheDataManage.INSTANCE.addData(FieldParamsInt.INFO_EDITABLE, isEditable);
            }
        }
        if (!isEditable) {
            new AlertDialog.Builder(context)
                    .setTitle(R.string.tips_title)
                    .setMessage(R.string.cannot_edit_now)
                    .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .create()
                    .show();
        }
        infoList.setVisibility(View.INVISIBLE);
        title.setText(getResources().getString(R.string.textview_field_contract_info));
//        findViewById(R.id.tv_contact).setSelected(true);
//        ((TimeLineView) findViewById(R.id.contact_node)).setCurrentStatus(TimeLineView.ACTIVE);

        mPresenter.requestDatas();


        updateSubmitButtonState();
        editTextChangeEvent();
        addEditableConfig();
//        new TraceSender().fetchPersonInfo(ContactInfoActivity.this,Manifest.permission.READ_CONTACTS, Manifest.permission.READ_CALL_LOG);
        mPresenter.requestPermission();

        contactInfoSubmit.setOnTouchListener((v, event) -> {
            if (!contactInfoSubmit.isClickable()) {
                String ret = checkUnFillContent();
                if (ret != null) {
                    XLeoToast.makeText(ContactInfoActivity.this, ret, Toast.LENGTH_SHORT).show();
                }
            }
            return false;
        });

        parentPhone.setItemOnClickListener(this::getParentInfo);
        friendPhone.setItemOnClickListener(this::getFriendInfo);


        if (!stepViewVisible) {
            stepView.setVisibility(View.GONE);
            return;
        }
        List<StepBean> stepsBeanList = new ArrayList<>();
        StepBean stepBean0 = new StepBean("Identification", StepBean.STEP_COMPLETED);
        StepBean stepBean1 = new StepBean("Personal Info", StepBean.STEP_COMPLETED);
        StepBean stepBean2 = new StepBean("Contact Info", StepBean.STEP_CURRENT);
        StepBean stepBean3 = new StepBean("Job Info", StepBean.STEP_UNDO);
        stepsBeanList.add(stepBean0);
        stepsBeanList.add(stepBean1);
        stepsBeanList.add(stepBean2);
        stepsBeanList.add(stepBean3);
        stepView.setStepViewTexts(stepsBeanList);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(SAVE_INSTANCE_IS_EDITABLE, isEditable);
    }

    private void addEditableConfig() {
        /*findViewById(R.id.ll_contactinfo_father).setClickable(isEditable);
        findViewById(R.id.ll_contactinfo_friend).setClickable(isEditable);
        findViewById(R.id.ll_friend_phone).setClickable(isEditable);
        findViewById(R.id.ll_parent_phone).setClickable(isEditable);*/
        if (!isEditable) {
            contactInfoSubmit.setSelected(true);
            contactInfoSubmit.setClickable(false);
        }
    }

    @Override
    protected ContactInfoActPresenter initPresenterImpl() {
        return new ContactInfoActPreImp();
    }

    //Text Change Listener

    private void editTextChangeEvent() {
//        Observable<CharSequence> observableParentName = RxTextView.textChanges(parentName);
        Observable<CharSequence> observableParentPhone = RxTextView.textChanges(parentPhone.getEditText());
//        Observable<CharSequence> observableFriendName = RxTextView.textChanges(friendName);
        Observable<CharSequence> observableFriendPhone = RxTextView.textChanges(friendPhone.getEditText());


        Observable.combineLatest(observableParentPhone, observableFriendPhone,
                (charSequence2, charSequence4) ->
                        !TextUtils.isEmpty(charSequence2.toString()) || !TextUtils.isEmpty(charSequence4.toString())).subscribe(aBoolean -> updateSubmitButtonState());
    }

    private void updateSubmitButtonState() {
        /*if (isCheckedField() && isEditable) {
            contactInfoSubmit.setClickable(true);
            contactInfoSubmit.setAlpha(0.8f);
        } else {
            contactInfoSubmit.setClickable(false);
            contactInfoSubmit.setAlpha(0.3f);
        }*/
    }

    public boolean isCheckedField() {
        if (TextUtils.isEmpty(parentName)) {
//            Toast.makeText(ContactInfoActivity.this, "Please input parent name.", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(parentPhone.getText().toString())) {
//            Toast.makeText(ContactInfoActivity.this, "Please input parent Phone.", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(friendName)) {
//            Toast.makeText(ContactInfoActivity.this, "Please input friend name.", Toast.LENGTH_SHORT).show();
            return false;
        }
        return !TextUtils.isEmpty(friendPhone.getText().toString());

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                Cursor cursor = getContentResolver()
                        .query(uri,
                                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER,
                                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                                null, null, null);
                while (cursor != null && cursor.moveToNext()) {
                    String number = cursor.getString(0);
                    String name = cursor.getString(1);
                    if (requestCode == 1) {
                        if (isContactSame(name, number, friendName, friendPhone.getText().toString())) {
                            parentName = "";
                            parentPhone.setText("");
                        } else {
                            parentName = name;
                            parentPhone.setText(number);
                        }

                    } else if (requestCode == 2) {
                        if (isContactSame(parentName, parentPhone.getText().toString(), name, number)) {
                            friendName = "";
                            friendPhone.setText("");
                        } else {
                            friendName = name;
                            friendPhone.setText(number);
                        }
                    }
                    XLog.INSTANCE.d("Result code: " + requestCode, 10);
                    XLog.INSTANCE.d("name: " + name + "number: " + number, 10);

                }
                cursor.close();
            }
        }
    }


    private boolean isContactSame(String parentName, String parentPhone, String friendName, String friendPhone) {
        parentPhone = parentPhone.trim().replace(" ", "");
        friendPhone = friendPhone.trim().replace(" ", "");

        if (!TextUtils.isEmpty(parentName) && !TextUtils.isEmpty(friendName) && !TextUtils.isEmpty(friendName) && !TextUtils.isEmpty(friendPhone)) {

            final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setTitle(getString(R.string.title_warning_tips));
            alertDialogBuilder.setNeutralButton(getString(R.string.msg_got_it_tips), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });


            if (parentName.equals(friendName)) {
                alertDialogBuilder.setMessage(getString(R.string.same_name));
                AlertDialog alertDialog = alertDialogBuilder.create();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        alertDialogBuilder.show();
                    }
                });
                return true;
            }

            if (parentPhone.equals(friendPhone)) {
                alertDialogBuilder.setMessage(getString(R.string.same_number));
                AlertDialog alertDialog = alertDialogBuilder.create();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        alertDialogBuilder.show();
                    }
                });
                return true;
            }

        }
        return false;
    }


    public void getParentInfo() {
        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.CONTACT_PARENT, null);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        } else {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, 1);
            }
        }
    }


    public void getFriendInfo() {
        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.CONTACT_FREND, null);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        } else {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, 2);
            }

        }
    }

    @OnClick(R.id.id_button_contact_info_submit)
    public void contactInfoSubmit() {
        if (isCheckedField()) {
            FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.BTN_CONTACT_INFO_SUBMIT, null);

            mPresenter.submitConatctInfo(parentName,
                    parentPhone.getText().toString(),
                    friendName,
                    friendPhone.getText().toString());
        }

    }

    @OnClick(R.id.id_imagebutton_back)
    public void back() {
        if (fromSplash) {
            startActivity(new Intent(this, IntroduceActivity.class));
        }
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }

    ContactInfoBean mContactInfoBean;

    @Override
    public void initView(ContactInfoBean contactInfoBean) {
        if (contactInfoBean != null) {
            parentName = contactInfoBean.getParentName();
            parentPhone.setText(contactInfoBean.getParentMobile());
            friendName = contactInfoBean.getFriendName();
            friendPhone.setText(contactInfoBean.getFriendMobile());

            mContactInfoBean = contactInfoBean;
        }

        ACache cache = ACache.get(this);
        String localParentName = cache.getAsString(getSaveKey(FieldParams.ContactField.PARENT_NAME));
        String localParentPhone = cache.getAsString(getSaveKey(FieldParams.ContactField.PARENT_PHONE));
        String localFriendName = cache.getAsString(getSaveKey(FieldParams.ContactField.FRIEND_NAME));
        String localFriendPhone = cache.getAsString(getSaveKey(FieldParams.ContactField.FRIEND_PHONE));

        if (!TextUtils.isEmpty(localParentName)) {
            parentName = localParentName;
        }

        if (!TextUtils.isEmpty(localParentPhone)) {
            parentPhone.setText(localParentPhone);
        }

        if (!TextUtils.isEmpty(localFriendName)) {
            friendName = localFriendName;
        }

        if (!TextUtils.isEmpty(localFriendPhone)) {
            friendPhone.setText(localFriendPhone);
        }
    }

    @Override
    public void onSubmitSuccess() {
        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.BTN_CONTACT_INFO_SUBMIT_SUCCESS, null);
        ContactInfoActivity.this.setResult(Activity.RESULT_OK);
        startActivity(new Intent(this, ProfessionalInfoActivity.class).putExtra(FieldParams.NOT_FINISH_CERTIFY, notFinish));
        if (!notFinish) {
            finish();
        }

        removeAllLocal();
    }

    private String checkUnFillContent() {
        if (TextUtils.isEmpty(parentName)) {
            return getString(R.string.enter_contact_information);
        }

        if (TextUtils.isEmpty(friendName)) {
            return getString(R.string.enter_contact_information);
        }
        return null;
    }


    private boolean localInputExist() {
        return !TextUtils.isEmpty(parentName)
                || !TextUtils.isEmpty(parentPhone.getText().toString())
                || !TextUtils.isEmpty(friendName)
                || !TextUtils.isEmpty(friendPhone.getText().toString()
        );
    }

    /**
     * 检查本地输入是否和服务器的相同
     */
    private boolean identicalToServer() {

        //都相同，返回true
        if (mContactInfoBean != null) {
            String[] serverValues = new String[]{
                    mContactInfoBean.getParentName(),
                    mContactInfoBean.getParentMobile(),
                    mContactInfoBean.getFriendName(),
                    mContactInfoBean.getFriendMobile()
            };

            String[] localValues = new String[]{
                    parentName,
                    parentPhone.getText().toString(),
                    friendName,
                    friendPhone.getText().toString()
            };

            return Arrays.equals(serverValues, localValues);
        }

        return false;
    }

    private void saveLocalInput() {
        ACache cache = ACache.get(this);

        if (!TextUtils.isEmpty(parentName)) {
            cache.put(getSaveKey(FieldParams.ContactField.PARENT_NAME), parentName);
        } else {
            cache.remove(getSaveKey(FieldParams.ContactField.PARENT_NAME));
        }

        if (!TextUtils.isEmpty(parentPhone.getText().toString())) {
            cache.put(getSaveKey(FieldParams.ContactField.PARENT_PHONE), parentPhone.getText().toString());
        } else {
            cache.remove(getSaveKey(FieldParams.ContactField.PARENT_PHONE));
        }

        if (!TextUtils.isEmpty(friendName)) {
            cache.put(getSaveKey(FieldParams.ContactField.FRIEND_NAME), friendName);
        } else {
            cache.remove(getSaveKey(FieldParams.ContactField.FRIEND_NAME));
        }

        if (!TextUtils.isEmpty(friendPhone.getText().toString())) {
            cache.put(getSaveKey(FieldParams.ContactField.FRIEND_PHONE), friendPhone.getText().toString());
        } else {
            cache.remove(getSaveKey(FieldParams.ContactField.FRIEND_PHONE));
        }
    }

    private void removeAllLocal() {
        ACache cache = ACache.get(this);
        cache.remove(getSaveKey(FieldParams.ContactField.PARENT_NAME));
        cache.remove(getSaveKey(FieldParams.ContactField.PARENT_PHONE));
        cache.remove(getSaveKey(FieldParams.ContactField.FRIEND_NAME));
        cache.remove(getSaveKey(FieldParams.ContactField.FRIEND_PHONE));
    }

    private String getSaveKey(String key) {
        return key + TokenManager.getInstance().getMobile();
    }
}

